<template>
  <div class="search-form-wrapper pt-4 mb-4" :style="{ '--form-item-padding': gutter / 2 + 'px' }">
    <div class="flex justify-between">
      <div ref="containerRef" style="display: flex; flex-wrap: wrap;">
        <div v-for="(vnode, index) in slots.default?.()" :key="index" :class="[
          !isExpanded && index >= defaultVisibleCount ? 'hidden-item' : '',
          'search-item'
        ]">
          <component :is="vnode" />
        </div>
      </div>
      <div class="search-action">
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-link v-if="showToggle" class="ml4" type="primary" :underline="false" @click="isExpanded = !isExpanded">
          {{ isExpanded ? '收起' : '展开' }}
          <el-icon :name="isExpanded ? 'arrow-up' : 'arrow-down'" />
        </el-link>
      </div>
    </div>
    <div class="h-1 bg-#f8f8f8"></div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, useSlots, nextTick, defineExpose } from 'vue'

defineProps({
  gutter: {
    type: Number,
    default: 20
  }
})

const slots = useSlots()
const containerRef = ref(null)
const defaultVisibleCount = ref(30)
const isExpanded = ref(false)
const prevWidth = ref(0)

// 获取容器宽度
const updateVisibleCount = () => {
  if (!containerRef.value) return
  const width = containerRef.value.offsetWidth
  if (Math.abs(width - prevWidth.value) > 50) {
    defaultVisibleCount.value = Math.floor((width - 232) / 256)
    prevWidth.value = width
  }
}

// ResizeObserver 优化版
const resizeObserver = new ResizeObserver(entries => {
  updateVisibleCount()
  nextTick(() => {
    isExpanded.value = false // 重置展开状态
  })
})

onMounted(() => {
  containerRef.value = document.querySelector('.page-container')
  if (containerRef.value) {
    resizeObserver.observe(containerRef.value)
  }
})

onUnmounted(() => {
  resizeObserver.disconnect()
})

// 热更新修复
defineExpose({ 
  refresh: () => {
    updateVisibleCount()
    nextTick(() => {
      formItemCount.value = slots.default?.().length || 0
    })
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(() => {
    nextTick(() => {
      refresh()
    })
  })
}
</script>

<style lang="scss" scoped>
.search-form-wrapper {
  .search-item {
    min-width: 240px;
    transition: all 0.3s ease;
  }

  .search-action {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  :deep(.hidden-item) {
    opacity: 0 !important;
    height: 0 !important;
    padding: 0 !important;
    margin: 0 !important;
    overflow: hidden !important;
  }

  :deep(.el-form-item) {
    margin-right: 16px !important;
    width: 240px !important;
  }
}
</style>